<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      
      <el-form-item label="选择物资" prop="assetName">

         <el-select
        class="!w-full"
        v-model="formData.assetName"
        clearable
        @change="onChangeFixed($event)"
        placeholder="请选择物资"
      >
        <el-option
          v-for="fixed in fixedList"
          :key="fixed.assetName"
          :label="fixed.assetName"
          :value="fixed.assetName"
          />
        </el-select>

      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item label="实际数量" prop="actualQuantity">
            <el-input-number v-model="formData.actualQuantity" :min="0" clearable controls-position="right" class="!w-1/1"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库存数量" prop="stockQuantity" >
            <el-input-number v-model="formData.stockQuantity" :min="0" clearable controls-position="right" class="!w-1/1" :disabled="true"/>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="12">
          <el-form-item label="差额" prop="difference">
            <el-input-number v-model="formData.difference" :min="-Infinity" clearable controls-position="right" class="!w-1/1" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="调整类型" prop="adjustmentType">
            <el-select v-model="formData.adjustmentType" placeholder="请选择调整类型" :disabled="true">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SCHOOL_ASSET_ADJUSTMENT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      
      <el-form-item v-if="formType == 'update'" label="库存调整" prop="adjustmentStatus">
        <el-select v-model="formData.adjustmentStatus" placeholder="请选择库存调整状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SCHOOL_ASSET_ADJUSTMENT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

     
      
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { AssetsCheckApi, AssetsCheckVO } from '@/api/school/assets/check'
import { AssetsFixedApi, AssetsFixedSimpleVO } from '@/api/school/assets/fixed'

/** 物资盘点 表单 */
defineOptions({ name: 'AssetsCheckForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  categoryId: undefined,
  assetType: 0,
  assetId: undefined,
  assetCode: undefined,
  assetName: undefined,
  stockQuantity: undefined,
  actualQuantity: undefined,
  difference: undefined,
  adjustmentStatus: undefined,
  adjustmentType: undefined,
  price: undefined,
  status: undefined,
  remark: undefined,
})
const formRules = reactive({
  categoryId: [{ required: true, message: '分类ID不能为空', trigger: 'blur' }],
  assetType: [{ required: true, message: '物资类型不能为空', trigger: 'change' }],
  assetId: [{ required: true, message: '物资ID不能为空', trigger: 'blur' }],
  assetName: [{ required: true, message: '物资名称不能为空', trigger: 'blur' }],
  stockQuantity: [{ required: true, message: '库存数量不能为空', trigger: 'blur' }],
  actualQuantity: [{ required: true, message: '实际数量不能为空', trigger: 'blur' }],
  difference: [{ required: true, message: '差额不能为空', trigger: 'blur' }],
  adjustmentStatus: [{ required: true, message: '库存调整状态不能为空', trigger: 'blur' }],
  adjustmentType: [{ required: true, message: '调整类型不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const fixedList = ref([] as AssetsFixedSimpleVO[]) //物资列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AssetsCheckApi.getAssetsCheck(id)
    } finally {
      formLoading.value = false
    }
  }

  //查询物资列表
  fixedList.value = await AssetsFixedApi.getAssetsFixedList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AssetsCheckVO
    if (formType.value === 'create') {
      await AssetsCheckApi.createAssetsCheck(data)
      message.success(t('common.createSuccess'))
    } else {
      await AssetsCheckApi.updateAssetsCheck(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 处理物资变更 */
const onChangeFixed = (assetName) => {
  const selected = fixedList.value.find(item => item.assetName === assetName);
    if (selected) {
      formData.value.categoryId = selected.categoryId;
      formData.value.stockQuantity = selected.assetQuantity;
      formData.value.actualQuantity = selected.assetQuantity;
      formData.value.difference = 0;
    } 
}

//监听实际库存的变化
watch(
  () => formData.value.actualQuantity,
  (newVal) => {
    const stock = formData.value.stockQuantity;
    const diff = newVal - stock;
    formData.value.difference = diff;
    // 判断差额类型
    if (diff > 0) {
      formData.value.adjustmentType = 1;
    } else if (diff < 0) {
      formData.value.adjustmentType = 2;
    } else {
      formData.value.adjustmentType = 0;
    }
    console.log('差额:', diff); 
  }
);

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    categoryId: undefined,
    assetType: 0,
    assetId: undefined,
    assetCode: undefined,
    assetName: undefined,
    stockQuantity: undefined,
    actualQuantity: undefined,
    difference: undefined,
    adjustmentStatus: undefined,
    adjustmentType: undefined,
    price: undefined,
    status: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>